package com.sen.gulimall.seckill.service.impl;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.google.common.collect.Lists;
import com.sen.common.constant.OrderConstant;
import com.sen.common.to.mq.SeckillOrderTo;
import com.sen.common.utils.R;
import com.sen.common.vo.MemberRespVo;
import com.sen.gulimall.seckill.feign.CouponFeignService;
import com.sen.gulimall.seckill.feign.ProductFeignService;
import com.sen.gulimall.seckill.interceptor.LoginUserInterceptor;
import com.sen.gulimall.seckill.service.SeckillService;
import com.sen.gulimall.seckill.to.SeckillSkuRedisTo;
import com.sen.gulimall.seckill.utils.MQSenderUtil;
import com.sen.gulimall.seckill.vo.SeckillSessionWithSkusVo;
import com.sen.gulimall.seckill.vo.SeckillSkuVo;
import com.sen.gulimall.seckill.vo.SkuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author Kisen
 * @email lqs0911@qq.com
 * @date 2023/1/31 14:40
 * @detail
 */
@Slf4j
@Service
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private MQSenderUtil mqSenderUtil;

    private final String SESSION_CACHE_PREFIX = "seckill:sessions:";

    private final String SECKILL_CHARE_PREFIX = "seckill:skus";

    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:"; //+商品随机码

    @Override
    public void uploadSeckillSkuLastest3Days() {
        //1、扫描最近三天的商品需要参加秒杀的活动
        R r = couponFeignService.getLatest3DaySession();
        if (r.getCode() == 0) {
            //上架商品
            List<SeckillSessionWithSkusVo> sessionData = r.getData(new TypeReference<List<SeckillSessionWithSkusVo>>() {
            });
            //缓存到Redis
            //1、缓存活动信息
            saveSessionInfos(sessionData);

            //2、缓存活动的关联商品信息
            saveSessionSkuInfo(sessionData);

        }
    }

    public List<SeckillSkuRedisTo> blockHandler(BlockException e) {
        log.error("getCurrentSeckillSkusResource被限流了...{}", e);
        return null;
    }

    /**
     * 返回当前时间可以参与的秒杀商品信息
     *
     * @return
     */
    @SentinelResource(value = "getCurrentSeckillSkusResource", blockHandler = "blockHandler")
    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
        List<SeckillSkuRedisTo> redisTos = Lists.newArrayList();
        //1、确定当前时间属于哪个秒杀场次
        long time = new Date().getTime();

        try (Entry entry = SphU.entry("seckillSkus")) {
            Set<String> keys = redisTemplate.keys(SESSION_CACHE_PREFIX + "*");
            for (String key : keys) {
                String replace = key.replace(SESSION_CACHE_PREFIX, "");
                String[] s = replace.split("_");
                long start = Long.parseLong(s[0]);
                long end = Long.parseLong(s[1]);

                if (time >= start && time <= end) {
                    //2、获取这个秒杀场次需要的所有商品信息
                    List<String> range = redisTemplate.opsForList().range(key, 0, -1);
                    BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SECKILL_CHARE_PREFIX);
                    List<String> list = ops.multiGet(range);
                    if (CollectionUtils.isNotEmpty(list)) {
                        List<SeckillSkuRedisTo> collect = list.stream().map(item -> {
                            SeckillSkuRedisTo redisTo = JSON.parseObject(item, SeckillSkuRedisTo.class);
//                        redisTo.setRandomCode(null); //当前秒杀开始就需要随机码
                            return redisTo;
                        }).collect(Collectors.toList());
                        redisTos.addAll(collect);
                    }
                }
            }
        } catch (BlockException e) {
            log.error("资源被限流，{}", e.getMessage());
        }

        return redisTos;
    }

    @Override
    public SeckillSkuRedisTo getSkuSeckillInfo(Long skuId) {
        //1、找到所有需要参与秒杀的商品的key
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SECKILL_CHARE_PREFIX);
        Set<String> keys = hashOps.keys();
        if (CollectionUtils.isNotEmpty(keys)) {
            //3_31
            String regx = "\\d_" + skuId;
            long current = new Date().getTime();
            for (String key : keys) {
                if (Pattern.matches(regx, key)) {
                    String json = hashOps.get(key);
                    SeckillSkuRedisTo redisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);
                    if (current < redisTo.getStartTime() || current > redisTo.getEndTime()) {
                        redisTo.setRandomCode(null);
                    }
                    return redisTo;
                }
            }
        }

        return null;
    }

    //TODO 上架秒杀商品的时候，每一个数据都有过期时间。
    //TODO 秒杀后续的流程，简化了收获地址等信息。
    @Override
    public String kill(String killId, String key, Integer num) {
        long start = System.currentTimeMillis();
        //1、获取当前商品的详细信息
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SECKILL_CHARE_PREFIX);
        String json = hashOps.get(killId);
        if (StringUtils.isEmpty(json)) {
            return null;
        }

        SeckillSkuRedisTo redisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);
        //校验合法性
        long current = new Date().getTime();
        Long startTime = redisTo.getStartTime();
        Long endTime = redisTo.getEndTime();
        long ttl = endTime - startTime;
        //1、校验时间的合法性
        if (current < startTime || current > endTime) {
            return null;
        }
        //2、校验随机码和商品id
        String randomCode = redisTo.getRandomCode();
        String skuId = redisTo.getPromotionSessionId() + "_" + redisTo.getSkuId();
        if (!randomCode.equals(key) || !skuId.equals(killId)) {
            return null;
        }
        //3、验证购物数量是否合理
        if (num > redisTo.getSeckillLimit()) {
            return null;
        }
        //4、验证这个人是否已经购买过。幂等性，只要秒杀成功，就去占位：userId_sessionId_skuId
        // SETNX
        MemberRespVo respVo = LoginUserInterceptor.loginUser.get();
        String redisKey = respVo.getId() + "_" + skuId;
        //自动过期
        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
        if (!aBoolean) {
            //占位失败，说明已经买过了
            return null;
        }
        RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
        boolean b = semaphore.tryAcquire(num);
        if (!b) {
            return null;
        }
        //秒杀成功
        //快速下单，发送MQ消息，10ms
        String timeId = IdWorker.getTimeId();
        SeckillOrderTo orderTo = new SeckillOrderTo();
        orderTo.setOrderSn(timeId);
        orderTo.setMemberId(respVo.getId());
        orderTo.setPromotionSessionId(redisTo.getPromotionSessionId());
        orderTo.setSkuId(redisTo.getSkuId());
        orderTo.setSeckillPrice(redisTo.getSeckillPrice());
        orderTo.setNum(num);
        mqSenderUtil.sendMessage(OrderConstant.ORDER_EVENT_EXCHANGE, OrderConstant.ORDER_SECKILL_ORDER_ROUTING_KEY, orderTo);

        long end = System.currentTimeMillis();
        log.info("耗时..." + (end - start));
        return timeId;

    }

    private void saveSessionInfos(List<SeckillSessionWithSkusVo> sessionData) {
        for (SeckillSessionWithSkusVo session : sessionData) {
            long startTime = session.getStartTime().getTime();
            long endTime = session.getEndTime().getTime();
            String key = SESSION_CACHE_PREFIX + startTime + "_" + endTime;
            Boolean hasKey = redisTemplate.hasKey(key);
            if (!hasKey) {
                List<String> collect = session.getRelationSkus().stream().map(item -> item.getPromotionSessionId() + "_" + item.getSkuId()).collect(Collectors.toList());
                //缓存活动信息
                redisTemplate.opsForList().leftPushAll(key, collect);
            }
        }
    }

    private void saveSessionSkuInfo(List<SeckillSessionWithSkusVo> sessionData) {
        for (SeckillSessionWithSkusVo session : sessionData) {
            //准备hash操作
            BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(SECKILL_CHARE_PREFIX);
            for (SeckillSkuVo relationSkus : session.getRelationSkus()) {
                String key = relationSkus.getPromotionSessionId() + "_" + relationSkus.getSkuId();

                if (!ops.hasKey(key)) {
                    //缓存商品
                    SeckillSkuRedisTo redisTo = new SeckillSkuRedisTo();
                    //1、sku的基本信息
                    R skuInfo = productFeignService.getSkuInfo(relationSkus.getSkuId());
                    if (skuInfo.getCode() == 0) {
                        SkuInfoVo info = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                        });
                        redisTo.setSkuInfo(info);
                    }

                    //2、sku的秒杀信息
                    BeanUtils.copyProperties(relationSkus, redisTo);

                    //3、设置上当前商品的秒杀时间
                    redisTo.setStartTime(session.getStartTime().getTime());
                    redisTo.setEndTime(session.getEndTime().getTime());

                    //4、随机码？ seckill?skuId=2&key=lkoidfsfnsd
                    String token = UUID.randomUUID().toString().replace("-", "");
                    redisTo.setRandomCode(token);

                    //如果当前这个场次的商品的库存信息已经上架就不需要上架
                    //5、使用库存作为分布式的信号量 限流
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                    //商品秒杀的数量作为信号量
                    semaphore.trySetPermits(relationSkus.getSeckillCount());

                    String jsonString = JSON.toJSONString(redisTo);
                    ops.put(key, jsonString);
                }

            }
        }
    }
}
